// 使用urlencod 入参

var bodyParser = require('body-parser')

var urlencodedParser = bodyParser.urlencoded({extended: false});

var mongoose = require('mongoose');

// mongoose.connect('mongodb+srv://luopangpang:luopangpang0812.@sanbox-xiaom.mongodb.net/test?retryWrites=true&w=majority', {useNewUrlParser: true});
mongoose.connect('mongodb://localhost/nodejs', {useNewUrlParser: true});

var todoSchema = new mongoose.Schema({
    item: String
});

var Todo = mongoose.model('Todo', todoSchema);

module.exports = function (app) {

    // 渲染页面
    app.get('/todo', function (req, res, next) {
        Todo.find({}, function (err, data) {
            if (err) throw err;
            res.render('todo', {todos: data});
        });
    })


    // 新增
    app.post('/todo', urlencodedParser, function (req, res, next) {
        var todo = new Todo({
            item: req.body.item
        });
        todo.save(function (err, data) {
            if (err) throw err;
            res.send('ok')
        })
    })

    // 删除
    app.delete('/todo/:item', function (req, res, next) {
        var deleteItem = req.params.item.trim().replace(/-/g, " ");
        Todo.deleteOne({ item: deleteItem }, function (err) {
            if (err) throw err;
            res.send('delete');
        });

    })
}
